package com.biao.hashmap;

import java.util.LinkedHashMap;
import java.util.Map;

public class Demo09_Lru_remove_cache {
    public static class LruCache<K, V> extends LinkedHashMap<K, V> {
        /**
         * 容量
         */
        private int capacity;

        public LruCache(int capacity) {
            super(capacity, 0.75f, true);
            this.capacity = capacity;
        }

        /**
         * 如果超过设置的存储容量则清除
         *
         * @param eldest
         * @return
         */
        @Override
        protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
            return size() > capacity;
        }
    }

    public static void main(String[] args) {
        LruCache<String, String> lruCache = new LruCache<>(3);
        lruCache.put("a", "a");
        lruCache.put("b", "b");
        lruCache.put("c", "c");

        lruCache.put("d", "d");

        lruCache.forEach((k, v) -> System.out.println("k: " + k + ", v: " + v));

        // 元素a被删除
    }
}